package com.example.administrator.homeworkintent;
import android.media.AudioManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
import com.example.administrator.homeworkintent.MusinInformation;
import com.example.administrator.homeworkintent.MusicList;

/**
 * Created by Administrator on 2017/10/27.
 */

public class SongKeep extends AppCompatActivity {
    private ImageButton imgBtn_Previous;
    private ImageButton imgBtn_PlayOrPause;
    private ImageButton imgBtn_Stop;
    private ImageButton imgBtn_Next;
    private ListView list;
    private SeekBar seekBar;
    /*   private TextView textView;*/
    private int playmode;
    private ArrayList<MusinInformation> musicArrayList;
    private int number = 0;
    private int status;
    private StatusChangedReceiver receiver;
    private TextView CurrentTime;
    private TextView DuraTime;
    private RelativeLayout bglayout;
    private int time;
    private int duration;
    private Handler seekBarHandler;
    private static boolean isExit=false;
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;
    private static final int MODE_SINGAL_LOOP = 0;
    private static final int MODE_LIST_LOOP = 1;
    private static final int MODE_LIST_SEQUENCE = 2;
    private TextView seekBar_Name;
    private SeekBar seekBar_Volumn;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_songs_keep);
        findViews();
        registerListeners();
        initMusicList();
        initListView();
        checkMusicfile();
        duration=0;
        time=0;
        bindStatusChangedReceiver();
        initSeekBarHandler();
        startService(new Intent(this, MusicService.class));
        status = MusicService.COMMAND_STOP;
    }
    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(
                MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }
    private void findViews() {
        imgBtn_Previous = (ImageButton) findViewById(R.id.imagebotton1);
        imgBtn_PlayOrPause = (ImageButton) findViewById(R.id.imagebotton2);
        imgBtn_Stop = (ImageButton) findViewById(R.id.imagebotton3);
        imgBtn_Next = (ImageButton) findViewById(R.id.imagebotton4);
        list = (ListView) findViewById(R.id.songlist);
        CurrentTime= (TextView) findViewById(R.id.time1);
        DuraTime= (TextView) findViewById(R.id.time2);
        seekBar= (SeekBar) findViewById(R.id.seekbar1);
        bglayout= (RelativeLayout) findViewById(R.id.rootlayout);
        seekBar_Name= (TextView) findViewById(R.id.volumn_text);
        seekBar_Volumn= (SeekBar) findViewById(R.id.volumn_seekbar);
    }

    private void registerListeners() {
        imgBtn_Previous.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);
            }
        });
        imgBtn_PlayOrPause.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    default:
                        break;
                }
            }
        });
        imgBtn_Stop.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);
            }
        });
        imgBtn_Next.setOnClickListener(new OnClickListener() {
            public void onClick(View view) {
                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
            }
        });
        list.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                number = position;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(status!=MusicService.STATUS_STOPPED){
                    time=seekBar.getProgress();
                    CurrentTime.setText(formatTime(time));
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if(status==MusicService.STATUS_PLAYING){
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }
            }
        });
    }
    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();
        if(musicArrayList.isEmpty())
        {
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //唱片
            int indexAlbum = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM);
            //总时长
            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);
            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()) {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strAlbum = mMusicCursor.getString(indexAlbum);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);
                if (strArtist.equals("<unknown>"))
                    strArtist = "无艺术家";
                if (strAlbum.equals("<unknown>"))
                    strAlbum = "无唱片";
                MusinInformation music = new MusinInformation(strTitle, strArtist, strAlbum, strPath, strTotoalTime);
                musicArrayList.add(music);
            }
        }
    }
    private void initListView() {
        List<Map<String, String>> list_map = new ArrayList<Map<String, String>>();
        HashMap<String, String> map;
        SimpleAdapter simpleAdapter;
        for (MusinInformation music : musicArrayList) {
            map = new HashMap<String, String>();
            map.put("musicName", music.getSongName());
            map.put("musicArtist", music.getSongArtist());
            map.put("musicAlbum", music.getSongAlbum());
            list_map.add(map);
        }
        String[] from = new String[] { "musicName", "musicArtist" ,"musicAlbum"};
        int[] to = { R.id.listview_name_item, R.id.listview_artist_item, R.id.listview_album_item};
        simpleAdapter = new SimpleAdapter(this, list_map, R.layout.listview,from, to);
        list.setAdapter(simpleAdapter);
    }
    private void checkMusicfile()
    {
        if (musicArrayList.isEmpty()) {
            imgBtn_Next.setEnabled(false);
            imgBtn_PlayOrPause.setEnabled(false);
            imgBtn_Previous.setEnabled(false);
            imgBtn_Stop.setEnabled(false);
            Toast.makeText(getApplicationContext(), "当前没有歌曲文件",Toast.LENGTH_SHORT).show();
        } else {
            imgBtn_Next.setEnabled(true);
            imgBtn_PlayOrPause.setEnabled(true);
            imgBtn_Previous.setEnabled(true);
            imgBtn_Stop.setEnabled(true);
        }
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();;
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        KeepThemes potthemes=new KeepThemes(SongKeep.this);
        String chosethe=potthemes.gettheme();
        setTheme(chosethe);
        audio_control();
    }
    private String formatTime(int smec){
        int minute= smec / 1000 / 60;
        int second= smec / 1000 % 60;
        String minuteString;
        String secondString;
        if(minute < 10){
            minuteString="0"+minute;
        }
        else{
            minuteString=""+minute;
        }
        if(second < 10){
            secondString="0"+second;
        }
        else{
            secondString=""+second;
        }
        return minuteString + ":" + secondString;
    }
    private void sendBroadcastOnCommand(int command) {
        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        switch (command) {
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time", time);
                break;
            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }
    class StatusChangedReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String musicName = intent.getStringExtra("musicName");
            String musicArtist = intent.getStringExtra("musicArtist");
            String musicAlbum = intent.getStringExtra("musicAlbum");
            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    list.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000L);
                    DuraTime.setText(formatTime(duration));
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.pause);
                    //设置textview文字，提示已经播放的歌曲
                    SongKeep.this.setTitle("正在播放:" + musicName + " - " + musicArtist + " - " + musicAlbum);
                    break;
                case MusicService.STATUS_PAUSED:
                    seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    SongKeep.this.setTitle(musicName + " - " + musicArtist + " - " + musicAlbum);
                    break;
                case MusicService.STATUS_STOPPED:
                    time = 0;
                    duration = 0;
                    CurrentTime.setText(formatTime(time));
                    DuraTime.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    SongKeep.this.setTitle("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                case MusicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);
                    if (playmode == SongKeep.MODE_SINGAL_LOOP){
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    }
                    else
                    if (playmode == SongKeep.MODE_LIST_LOOP){
                        if (number == MusicList.getMusicList().size() - 1)
                        {   number=0;
                            sendBroadcastOnCommand(MusicService.STATUS_PLAYING);}
                        else
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    }
                    else
                    if(playmode == SongKeep.MODE_LIST_SEQUENCE){
                        if (number == MusicList.getMusicList().size() - 1)
                            sendBroadcastOnCommand(MusicService.STATUS_STOPPED);
                        else
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    }
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    SongKeep.this.setTitle("");
                    imgBtn_PlayOrPause.setBackgroundResource(R.drawable.play);
                    break;
                default:
                    break;
            }
        }
    }
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (status == MusicService.STATUS_STOPPED) {
            stopService(new Intent(this, MusicService.class));
        }
        super.onDestroy();
    }
    private void setTheme(String theme){
        if("冰雪".equals(theme)){
            bglayout.setBackgroundResource(R.drawable.bg_snow);
        }
        if("山脉".equals(theme)){
            bglayout.setBackgroundResource(R.drawable.bg_mountain);
        }
        if("花朵".equals(theme)){
            bglayout.setBackgroundResource(R.drawable.bg_digit_flower);
        }
        if("女生".equals(theme)){
            bglayout.setBackgroundResource(R.drawable.bg_music_girl);
        }
        if("彩色".equals(theme)){
            bglayout.setBackgroundResource(R.drawable.bg_color);
        }
    }
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case R.id.menu_theme:
                new AlertDialog.Builder(this).setTitle("请选择主题").
                        setItems(R.array.chostheme, new android.content.DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String themes=KeepThemes.THEMES[which];
                                SongKeep.this.setTheme(themes);
                                KeepThemes numtheme=new KeepThemes(SongKeep.this);
                                numtheme.setAndSaveTheme(themes);
                            }
                        }).show();
                break;
            case R.id.menu_mode:
                String[] mode=new String[] { "单曲循环" , "列表循环" , "顺序播放" };
                AlertDialog.Builder builder=new AlertDialog.Builder(SongKeep.this);
                builder.setTitle("请选择模式");
                builder.setSingleChoiceItems(mode,playmode, new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int nummode) {
                        playmode=nummode;
                    }
                });
                builder.setPositiveButton("确定",new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch(playmode) {
                            case 0:
                                playmode = SongKeep.MODE_SINGAL_LOOP;
                                Toast.makeText(getApplicationContext(), "单曲循环", Toast.LENGTH_SHORT).show();
                                break;
                            case 1:
                                playmode = SongKeep.MODE_LIST_LOOP;
                                Toast.makeText(getApplicationContext(), "列表循环", Toast.LENGTH_SHORT).show();
                                break;
                            case 2:
                                playmode = SongKeep.MODE_LIST_SEQUENCE;
                                Toast.makeText(getApplicationContext(), "顺序播放", Toast.LENGTH_SHORT).show();
                                break;
                            default:
                                break;
                        }
                    }
                });
                builder.create().show();
                break;
            case R.id.menu_quit:
                new AlertDialog.Builder(this).setTitle("提示").setMessage("你确定要退出吗？")
                        .setPositiveButton("Yes", new android.content.DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                System.exit(0);
                            }
                        }).setNegativeButton("No", new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public boolean onKeyDown(int KeyCode, KeyEvent event){
        int progress;
        switch(KeyCode) {
            case KeyEvent.KEYCODE_BACK:
                exitByDoubleClick();
                break;
            case KeyEvent.KEYCODE_VOLUME_DOWN:
                progress=seekBar_Volumn.getProgress();
                if(progress!=0)
                    seekBar_Volumn.setProgress(progress-1);
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                progress=seekBar_Volumn.getProgress();
                if(progress!=seekBar_Volumn.getMax())
                    seekBar_Volumn.setProgress(progress+1);
                return true;
            default:
                break;
        }
        return false;
    }
    private void exitByDoubleClick(){
        Timer timer = null;
        if(isExit == false){
            isExit = true;
            Toast.makeText(this,"再按一次可退出",Toast.LENGTH_SHORT).show();
            timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit=false;
                }
            },2000);
        }
        else
        {
            System.exit(0);
        }
    }
    private void audio_control(){
        final AudioManager audioManager= (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        final int max_progress= audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekBar_Volumn.setMax(max_progress);
        int progress = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekBar_Volumn.setProgress(progress);
        seekBar_Name.setText("音量："+(progress*100/max_progress)+"%");
        seekBar_Volumn.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                seekBar_Name.setText("音量："+(progress*100/max_progress)+"%");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,progress,AudioManager.FLAG_PLAY_SOUND);
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }
    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            seekBar.setProgress(time);
                            seekBar.incrementProgressBy(1000);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            CurrentTime.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        break;
                    case PROGRESS_RESET:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        CurrentTime.setText("00:00");
                        break;
                }
            }
        };
    }
}
